package com.dogkr.server.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dogkr.common.Constants;
import com.dogkr.common.FileDirEnum;
import com.dogkr.common.FileUtils;
import com.dogkr.server.entity.User;
import com.dogkr.server.entity.UserMessage;
import com.dogkr.server.entity.UserPet;
import com.dogkr.server.entity.UserMessage.Read;
import com.dogkr.server.mapper.UserMapper;
import com.dogkr.server.mapper.UserMessageMapper;
import com.sean.common.exception.ServiceException;
import com.sean.common.page.Pagination;
import com.sean.common.page.ResultPagination;
import com.sean.common.service.BaseService;
import com.sean.common.utils.StringUtils;

@Service
public class UserService extends BaseService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private HostService hostService;

	/**
	 * 用户注册.
	 * @param user
	 */
	public void register(User user) {
		String loginName = user.getLoginName();
		if(!this.checkLonginName(loginName)) {
			user.setCreateDate(new Date());
			user.setLastModifydate(user.getCreateDate());
			user.setLastLogindate(user.getCreateDate());
			user.setStatus(Constants.STATUS_NORMAL);
			int ret = userMapper.insert(user);
			//hostService.insert(user.createHost());
			if(ret != 1) {
				throw new ServiceException("用户注册失败." + user);
			}
		}
	}
	
	/**
	 * 检查用户名是否存在.
	 * @param loginName
	 * @return
	 */
	public boolean checkLonginName(String loginName) {
		int count = userMapper.checkLonginName(loginName);
		if(count > 0) {
			return true;
		}
		return false;
	}

	public User selectByLoginName(String username) {
		return userMapper.selectByLoginName(username);
	}
	
	public int updateByPrimaryKeySelective(User user) {
		return userMapper.updateByPrimaryKeySelective(user);
	}
	/**
	 * 更新用户信息.
	 * @param user
	 * @throws IOException 
	 */
	public void updateUserInfo(User user, String oldFileName) {
		User updateUser = new User();
		updateUser.updateInfo(user);
		if(StringUtils.isNotBlank(user.getUserPhotoPath())) {
			try {
				FileUtils.removeUploadFile(user.getUserPhotoPath(), FileDirEnum.HEAD);
				updateUser.setUserPhotoPath(user.getUserPhotoPath());
				if(StringUtils.isNotBlank(oldFileName)){
					FileUtils.deleteUploadFile(oldFileName, FileDirEnum.HEAD);
				}
			} catch (IOException e) {
				log.error("用户头像移动失败.fileName:" + user.getUserPhotoPath(), e);
			}
		} else {
			updateUser.setUserPhotoPath(null);
		}
		userMapper.updateByPrimaryKeySelective(updateUser);
	}

	public void resetPassword(User user) {
		userMapper.updateByPrimaryKeySelective(user);
	}

	public User selectWithShow(Long id) {
		return userMapper.selectByPrimaryKeyWithShow(id);
	}

	public User selectByPrimaryKey(Long userId) {
		return userMapper.selectByPrimaryKey(userId);
	}
}
